from flask import Blueprint, render_template, request, url_for, session, g
from flask_login import login_required, login_user, logout_user
from flask_restful import reqparse, abort, Api, Resource
from functools import wraps
import datetime as dt
import re

from myflaskapp.user.models import User, Role, Sbu
from myflaskapp.extensions import auth, login_manager
from myflaskapp.api.views import check_role
from myflaskapp.mproject.models import Project, Stage, Work, Content, File, Log, Problem, Discussion, Post

blueprint = Blueprint(
    'mproject', __name__, static_folder='../static', static_url_path='')

api = Api(blueprint)

parser = reqparse.RequestParser()
parser.add_argument('username')
parser.add_argument('password')


class Getproject(Resource):
    @auth.login_required
    def get(self):
        projects = Project.query.all()
        infos = []
        for project in projects:
            info = {}
            info['name'] = project.name
            info['update_time'] = project.update_time.strftime(
                '%Y-%m-%d %H:%M:%S')
            info['start_time'] = project.start_time.strftime(
                '%Y-%m-%d %H:%M:%S')
            for stage in project.stages:
                if '进行中' in stage.state:
                    info['stage'] = stage.item
            if 'stage' not in info:
                info['stage'] = '未开展'
            infos.append(info)
        if not len(infos) == 0:
            return {'code': 20000, 'data': infos}
        else:
            return {'code': 0, 'message': '未开展任何项目，请新建！'}

    @auth.login_required
    def post(self):
        data = request.get_json()
        project = Project.create(name=data['name'], content=data['content'],
                       update_time=dt.datetime.now(), start_time=dt.datetime.now())
        logstring = '创建了%s'%(project.name)
        Log.create(log=logstring,create_time=dt.datetime.now(),project=project)
        return {'code': 20000, 'data': {'success': 1}}


class Pstages(Resource):
    @auth.login_required
    def get(self, project_name, pclass):
        rpdata = {}
        project = Project.query.filter_by(name=project_name).first()
        # 检查任务当前阶段
        current_stage = Stage.query.filter(
            Stage.project == project, Stage.state == '进行中').first()
        if current_stage is None:
            current_stage = Stage.query.filter(Stage.project == project,Stage.sequence == 1).first()
            if current_stage is None:
                return {'code': 0, 'message': '未设置任何项目阶段，请新建！'}
            else:
                current_stage.state = '进行中'
                current_stage.save()
        rpdata['current_stage'] = current_stage.sequence

        if pclass == 'stage' or pclass == 'all':
            rpdata['stages'] = []
            stages = Stage.query.filter_by(
                project=project).order_by(Stage.sequence).all()
            if stages is None:
                return {'code': 0, 'message': '未设置任何项目阶段，请新建！'}
            for stage in stages:
                stagedata = {}
                stagedata['item'] = stage.item
                stagedata['content'] = stage.content
                stagedata['sequence'] = stage.sequence
                stagedata['state'] = stage.state
                rpdata['stages'].append(stagedata)
        if pclass == 'works' or pclass == 'all':
            rpdata['works'] = []
            works = Work.query.filter_by(stage = current_stage).all()
            for work in works:
                workdata = {}
                workdata['id'] = work.id
                workdata['item'] = work.item
                rpdata['works'].append(workdata)
        if pclass == 'problems' or pclass == 'all':
            rpdata['problems'] = []
            problems = Problem.query.filter(Problem.project==project,Problem.state=='未解决').all()
            for problem in problems:
                problemdata = {}
                problemdata['id'] = problem.id
                problemdata['item'] = problem.item
                rpdata['problems'].append(problemdata)
        if pclass == 'posts' or pclass == 'all':
            rpdata['posts'] = []
            posts = Post.query.filter_by(project=project).order_by(Post.create_time).all()
            for post in posts:
                postdata = {}
                postdata['id'] = post.id
                postdata['item'] = post.title
                rpdata['posts'].append(postdata)
        if pclass == 'logs' or pclass == 'all':
            rpdata['logs'] = []
            logs = Log.query.filter_by(project=project).order_by(Log.create_time).all()
            for log in logs:
                logdata = {}
                logdata['content'] = log.log
                logdata['timestamp'] = log.create_time.strftime('%Y-%m-%d %H:%M:%S')
                rpdata['logs'].append(logdata)
        return {'code': 20000, 'data': rpdata}

    @auth.login_required
    def post(self, project_name, pclass):
        project = Project.query.filter_by(name=project_name).first()
        if pclass == 'stage' or pclass == 'all':
            data = request.get_json()
            if data['isEdit'] == 0:
                stage = Stage.create(item=data['item'], content=data['content'],
                             project=project, sequence=data['sequence'], state=data['state'])
                logstring = '创建了项目阶段：%s'%(stage.item)
                Log.create(log=logstring,create_time=dt.datetime.now(),project=project)
            else:
                stage = Stage.query.filter(
                    Stage.project == project, Stage.sequence == data['sequence']).first()
                stage.item = data['item']
                stage.content = data['content']
                stage.state = data['state']
                stage.save()
                logstring = '修改了项目阶段%s'%(stage.item)
                Log.create(log=logstring,create_time=dt.datetime.now(),project=project)
        elif pclass == 'create_work':
            data = request.get_json()
            stage = Stage.query.filter(
                Stage.item == data['stage'], Stage.project == project).first()
            work = Work.create(item=data['item'], content=data['content'], stage=stage,
                               update_time=dt.datetime.now(), start_time=dt.datetime.now())
            [Content.create(name=text, leixing=1, complete=0, work=work)
             for text in data['details']]
            [Content.create(name=text, leixing=2, complete=0, work=work)
             for text in data['targets']]
            logstring = '创建了项目任务%s'%(work.item)
            Log.create(log=logstring,create_time=dt.datetime.now(),project=project,workid=work.id)
        elif pclass == 'problem':
            data = request.get_json()
            user = User.query.filter_by(id=session['username']).first()
            problem = Problem.create(item=data['item'], content=data['content'], start_time=dt.datetime.now(
            ), state='未解决', project=project, username=user.chinese_name)
            logstring = '创建了项目问题%s'%(problem.item)
            Log.create(log=logstring,create_time=dt.datetime.now(),project=project)
            return {'code': 20000, 'data': {'success': 1, 'id': problem.id}}
        elif pclass == 'createpost':
            data = request.get_json()
            user = User.query.filter_by(id=session['username']).first()
            post = Post.create(title=data['title'],content=data['articleContent'],project=project,username=user.chinese_name,create_time=dt.datetime.now())
            logstring = '提交了工作日志%s'%(post.title)
            Log.create(log=logstring,create_time=dt.datetime.now(),project=project)
            return {'code': 20000, 'data': {'success': 1, 'id': post.id}}

        return {'code': 20000, 'data': {'success': 1}}


class Getinfobyid(Resource):
    @auth.login_required
    def get(self, pclass, id):
        rpdata = {}
        if pclass == 'work':
            work = Work.query.filter_by(id=id).first()
            rpdata['id'] = work.id
            rpdata['item'] = work.item
            rpdata['content'] = work.content
            rpdata['state'] = work.state
            rpdata['update_time'] = work.update_time.strftime(
                '%Y-%m-%d %H:%M:%S')
            rpdata['start_time'] = work.start_time.strftime(
                '%Y-%m-%d %H:%M:%S')
            rpdata['username'] = work.username
            rpdata['contents'] = []
            rpdata['files'] = []
            rpdata['logs'] = []
            logs = Log.query.filter_by(workid=work.id).order_by(Log.create_time).all()
            for content in work.contents:
                data = {}
                data['id'] = content.id
                data['name'] = content.name
                data['leixing'] = content.leixing
                data['complete'] = content.complete
                rpdata['contents'].append(data)
            for f in work.files:
                data = {}
                data['id'] = f.id
                data['title'] = f.title
                data['url'] = f.url
                data['create_time'] = f.create_time.strftime(
                    '%Y-%m-%d %H:%M:%S')
                rpdata['files'].append(data)
            for log in logs:
                data = {}
                data['id'] = log.id
                data['log'] = log.log
                data['create_time'] = log.create_time.strftime(
                    '%Y-%m-%d %H:%M:%S')
                rpdata['logs'].append(data)
        if pclass == 'problem':
            problem = Problem.query.filter_by(id=id).first()
            rpdata['item'] = problem.item
            rpdata['content'] = problem.content
            rpdata['username'] = problem.username
            rpdata['startTime'] = problem.start_time.strftime(
                '%Y-%m-%d %H:%M:%S')
            rpdata['discussions'] = []
            for discussion in problem.discussions:
                data = {}
                data['content'] = discussion.content
                data['username'] = discussion.username
                data['startTime'] = discussion.create_time.strftime(
                    '%Y-%m-%d %H:%M:%S')
                rpdata['discussions'].append(data)
        if pclass == 'showpost':
            post = Post.query.filter_by(id=id).first()
            rpdata['title'] = post.title
            rpdata['content'] = post.content
            rpdata['username'] = post.username
            rpdata['createTime'] = post.create_time.strftime(
                '%Y-%m-%d %H:%M:%S')
            rpdata['project'] = post.project.name
        return {'code': 20000, 'data': rpdata}

    @auth.login_required
    def post(self, pclass, id):
        if pclass == 'work':
            data = request.get_json()
            work = Work.query.filter_by(id=id).first()
            if not work.state == data['state']:
                user = User.query.filter_by(id=session['username']).first()
                work.username = user.chinese_name
            work.state = data['state']
            work.save()
            for d in data['contents']:
                content = Content.query.filter_by(id=d['id']).first()
                content.complete = d['complete']
                content.save()
            logstring = '修改了工作任务%s'%(work.item)
            Log.create(log=logstring,create_time=dt.datetime.now(),project=work.stage.project,workid=work.id)
        if pclass == 'problem':
            data = request.get_json()
            problem = Problem.query.filter_by(id=id).first()
            user = User.query.filter_by(id=session['username']).first()
            Discussion.create(content=data['content'], create_time=dt.datetime.now(), username=user.chinese_name, problem=problem)
            logstring = '回复了问题%s'%(problem.item)
            Log.create(log=logstring,create_time=dt.datetime.now(),project=problem.project)
        if pclass == 'newfile':
            data = request.get_json()
            work = Work.query.filter_by(id=id).first()
            file = File.create(title=data['title'],url=data['url'],create_time=dt.datetime.now(),work=work)
            logstring = '%s增加了关联文档%s'%(work.item,file.title)
            Log.create(log=logstring,create_time=dt.datetime.now(),project=work.stage.project,workid=id)
        return {'code': 20000, 'data': {'success': 1}}


api.add_resource(Getproject, '/prod-api/mproject/project',
                 endpoint='getprojectapi')
api.add_resource(
    Pstages, '/prod-api/mproject/project/<project_name>/<pclass>', endpoint='getprojectinfos')
api.add_resource(
    Getinfobyid, '/prod-api/mproject/byid/<pclass>/<id>', endpoint='getinfosbyid')
